package com.xyauto.uilib.view;

import android.annotation.SuppressLint;
import android.app.WallpaperColors;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;


@SuppressLint("AppCompatCustomView")
public class WallpaperView extends ImageView {
    private static final String TAG = "WallpaperView";
    private Paint paint;
    private float wallpaperAlpha = 0f; // 默认完全不透明
    Context mContext;
    private static final String Action_DayNight = "xy.android.action.update_theme";
    private BroadcastReceiver mReceiver;
    private Mode mCurrentMode;
    private WallpaperManager mWallpaperManager;
    private int wallpaperIndex = 0;

    public enum Mode {
        Day,
        Night
    }

    public WallpaperView(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public WallpaperView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public WallpaperView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private BroadcastReceiver generaReceiver() {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //test
//                int flag = intent.getIntExtra("lamplet_state", 0);//0关灯,1开灯
//                if(flag == 0) {
//                    if(mSwitchListener != null) {
//                        mSwitchListener.onSwitch(Mode.Day);
//                    }
//                }else{
//                    if(mSwitchListener != null) {
//                        mSwitchListener.onSwitch(Mode.Night);
//                    }
//                }

                Mode mode = getCurrentMode(context);
                Log.i(TAG, "onReceive: " + mode.name());
                if (mode != mCurrentMode) {
                    mCurrentMode = mode;
                }
                if (mode == Mode.Night) {
                    wallpaperAlpha = Settings.System.getInt(mContext.getContentResolver(), "wallpaper_alpha", 60);
                    setWallpaperAlpha(wallpaperAlpha);// 夜间根据系统壁纸透明度设置
                } else {
                    setWallpaperAlpha(0f);// 白天完全透明
                }
            }
        };
    }


    private static Mode getCurrentMode(Context context) {

        int themeMode = Settings.Secure.getInt(context.getContentResolver(), "theme_mode", 1);
        if (themeMode == 1) { //值为1
            //...浅色主题的逻辑
            return Mode.Day;
        } else {  //值为2
            //...深色主题的逻辑
            return Mode.Night;
        }
    }

    private void loadWallpaper() {
        Drawable wallpaperDrawable = mWallpaperManager.getDrawable();
        Log.d(TAG, "loadWallpaper: ");
        if (wallpaperDrawable != null) {
            setImageDrawable(wallpaperDrawable);
        } else {
            Log.w(TAG, "Failed to load wallpaper");
        }
    }

    @SuppressLint("NewApi")
    private WallpaperManager.OnColorsChangedListener mOnColorsChangedListener = new WallpaperManager.OnColorsChangedListener() {
        @SuppressLint("MissingPermission")
        @Override
        public void onColorsChanged(WallpaperColors colors, int which) {
            if (wallpaperIndex != which)
                loadWallpaper();
            wallpaperIndex=which;
        }
    };

    private void init() {
        setScaleType(ScaleType.FIT_XY);
        mWallpaperManager = (WallpaperManager) getContext().getSystemService(Context.WALLPAPER_SERVICE);

        // 直接加载并设置系统壁纸
        loadWallpaper();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            mWallpaperManager.addOnColorsChangedListener(mOnColorsChangedListener, new Handler());
        }
        mReceiver = generaReceiver();
        mContext.registerReceiver(mReceiver, new IntentFilter(Action_DayNight));
        mCurrentMode = getCurrentMode(mContext);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);


        if (mCurrentMode == Mode.Night) {
            wallpaperAlpha = Settings.System.getInt(mContext.getContentResolver(), "wallpaper_alpha", 75);
            setWallpaperAlpha(wallpaperAlpha);// 夜间根据系统壁纸透明度设置
        } else {
            setWallpaperAlpha(0f);// 白天完全透明
        }


    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();
        // 绘制黑色遮罩
        canvas.drawRect(0, 0, width, height, paint);

    }

    // 设置黑色遮罩透明度的方法
    public void setWallpaperAlpha(float alpha) {
        wallpaperAlpha = alpha / 100.f;
        Log.d("TAG", "setWallpaperAlpha: " + wallpaperAlpha);
        paint.setAlpha((int) (255 * wallpaperAlpha));
        invalidate(); // 通知视图重绘
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            mWallpaperManager.removeOnColorsChangedListener(mOnColorsChangedListener);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            mWallpaperManager.addOnColorsChangedListener(mOnColorsChangedListener, new Handler());
        }
    }

}
